package middleware

import (
	"api/internal/types"
	"github.com/golangblogs/gojwt"
	"github.com/zeromicro/go-zero/rest/httpx"
	"net/http"
	"strconv"
)

type UserAgentMiddleware struct {
}

func NewUserAgentMiddleware() *UserAgentMiddleware {
	return &UserAgentMiddleware{}
}

func (m *UserAgentMiddleware) Handle(next http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// TODO generate middleware implement function, delete after code implementation
		token := r.Header.Get("token")
		if token == "" {
			response := types.Response{
				Msg:  "请输入token",
				Code: 500,
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		NewJWT := jwt.NewJWT("2301a")
		parseToken, err := NewJWT.ParseToken(token)
		if err != nil {
			response := types.Response{
				Msg:  "请输入token",
				Code: 500,
				Data: nil,
			}
			httpx.OkJsonCtx(r.Context(), w, response)
			return
		}
		r.ParseForm()
		r.Form.Set("userId", strconv.Itoa(int(parseToken.ID)))
		// Passthrough to next handler if need
		next(w, r)
	}
}
